package com.jeeplus.common.utils;

import com.jeeplus.modules.sys.entity.TreeModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @title: TreeDataMake
 * @projectName JeePlus
 * @description: TODO
 * @date 2019/10/2718:39
 */

public class TreeDataMake {
    public List<TreeModel> ToTree(List<TreeModel> list, String parentId) {
        Map<String, List<TreeModel>> childrenMap = new HashMap<>();
        Map<String, TreeModel> parentMap = new HashMap<>();
        List<TreeModel> res = new ArrayList<>();
        for (TreeModel node : list) {
            node.hasChildren = false;
            node.complete = true;
            if (!childrenMap.containsKey(node.parentId)) {
                childrenMap.put(node.parentId, new ArrayList<TreeModel>());
            } else if (parentMap.containsKey(node.parentId)) {
                parentMap.get(node.parentId).hasChildren = true;
            }
            childrenMap.get(node.parentId).add(node);
            // 注册父节点映射节点表
            parentMap.put(node.id, node);
            if (!childrenMap.containsKey(node.id)) {
                childrenMap.put(node.id, new ArrayList<TreeModel>());
            } else {
                node.hasChildren = true;
            }
            node.ChildNodes = childrenMap.get(node.id);
        }
        if (parentId.isEmpty()) {
            // 获取祖先数据列表
            for (List<TreeModel> item : childrenMap.values()) {
                for (TreeModel t : item) {
                    if (!parentMap.containsKey(t.parentId)) {
                        res.add(t);
                    }
                }
            }
        } else {
            if (childrenMap.containsKey(parentId)) {
                return childrenMap.get(parentId);
            } else {
                return new ArrayList<TreeModel>();
            }
        }
        return res;
    }
}
